package com.yuerenjf.yuerenjinfu.dialog;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.utils.FileUtils;
import com.yuerenjf.yuerenjinfu.utils.ImagePathUtil;

import org.xutils.common.util.LogUtil;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2015/10/19.
 */
public class DialogPicSelector extends Dialog implements View.OnClickListener {

    private Activity mContext;
    /* 头像名称 */
    private static final String IMAGE_FILE_NAME = "face.jpg";
    /* 请求码 */
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int SELECT_PIC_KITKAT = 3;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
    TypeCallBack callBack;


    public TypeCallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(TypeCallBack callBack) {
        this.callBack = callBack;
    }



    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static String imageDir = "temp.jpg";


    public DialogPicSelector(Activity context) {
        super(context, R.style.dialog);
        this.mContext = context;
        setCanceledOnTouchOutside(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_pic_selector);

        findViewById(R.id.photo).setOnClickListener(this);
        findViewById(R.id.local).setOnClickListener(this);
        findViewById(R.id.cancle).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.photo:
                takePhoto();
                break;
            case R.id.local:
                choosePhoto();

                break;
            case R.id.cancle:
                dismiss();
                break;
        }
    }



    public void showCustomDialog() {
        show();
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
    }


    public interface TypeCallBack {
        void setImageToView(Bitmap bitmap) throws IOException;
    }



    void openCamra(){
        Intent intentFromCapture = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (FileUtils.isSdCardMounted()) {
            intentFromCapture.putExtra(
                    MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment
                            .getExternalStorageDirectory(),
                            IMAGE_FILE_NAME)));
        }
        mContext.startActivityForResult(intentFromCapture,
                CAMERA_REQUEST_CODE);
    }


    public void activityForResult(int requestCode, int resultCode, Intent data){
        // 结果码不等于取消时候
        if (resultCode != mContext.RESULT_CANCELED) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;
                case SELECT_PIC_KITKAT:
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if (FileUtils.isSdCardMounted()) {
                        File tempFile = new File(Environment.getExternalStorageDirectory(),IMAGE_FILE_NAME);
                        startPhotoZoom(Uri.fromFile(tempFile));
                    }
                    break;
                case RESULT_REQUEST_CODE:
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            Bitmap photo = extras.getParcelable("data");

                            LogUtil.i(photo.getWidth()+"---"+photo.getHeight());
                            try {
                                callBack.setImageToView(photo);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
            }
        }
    }


    public void  onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        if(requestCode==222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamra();
            } else {
                Toast.makeText(mContext, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                        .show();
            }
        }
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                takePhoto();
            } else
            {
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                choosePhoto();
            } else
            {
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }



    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            return;
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            String url= ImagePathUtil.getPath(mContext,uri);
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
        }else{
            intent.setDataAndType(uri, "image/*");
        }
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        mContext.startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    private void takePhoto(){
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(mContext,new String[]{Manifest.permission.CAMERA},222);
                return;
            }else{
                openCamra();
            }
        } else {
            openCamra();
        }
    }


    private void choosePhoto(){
        Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            mContext.startActivityForResult(intent,SELECT_PIC_KITKAT);
        } else {
            mContext.startActivityForResult(intent,IMAGE_REQUEST_CODE);
        }
    }




}
